<template>
  <div class="container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-button
        type="primary"
        @click="openRegisterForm"
        color="#626aef"
        :icon="Plus"
        :disabled="percentage >= 100 ? true : false"
        >新建知识库</el-button
      >
      <el-input
        v-model="query_name"
        placeholder="请输入搜索内容"
        class="search-input"
        :prefix-icon="Search"
        clearable
        @change="inputKeySearch"
      />
    </div>

    <!-- 卡片展示部分 -->
    <div class="card-container">
      <el-card
        v-for="(card, index) in knowledges"
        :key="index"
        class="card"
        shadow="hover"
        @click="goToDetail(card.id)"
      >
        <!-- <template #header>{{
          truncateLabel(card.knowledge_name, 15)
        }}</template> -->
        <!-- 卡片头部 -->
        <template #header>
          <div class="card-header">
            <span>{{ truncateLabel(card.knowledge_name, 15) }}</span>
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="el-dropdown-link" @click.stop>
                <!-- 阻止事件冒泡 -->
                <el-icon><More /></el-icon>
                <!-- 三个点的图标 -->
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'detail', id: card.id }"
                    >详情</el-dropdown-item
                  >
                  <el-dropdown-item :command="{ action: 'delete', id: card.id }"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
        <p class="update-date">{{ truncateLabel(card.description, 25) }}</p>
        <p class="update-date">{{ formatDate(card.update_date) }}</p>
      </el-card>
    </div>
  </div>
  <!-- 翻页功能 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="limit"
      :size="limit"
      layout="prev, pager, next, jumper"
      :total="knowledges_content"
      @current-change="get_knowledge"
    />
  </div>

  <!-- 进度条部分 -->
  <div class="demo-progress">
    <div style="display: flex; align-items: center;">
    <p style="margin-right: 10px; white-space: nowrap;">知识库使用量：</p>
    <div style="flex: 1;">
      <el-progress
        :percentage="percentage"
        :color="customColorMethod"
        style="max-width: 30%; margin-top: 1px;"
        striped
        striped-flow
        duration="3"
        stroke-width="10"
      />
    </div>
  </div>
  </div>

  <!-- 新建知识库表单抽屉 -->
  <form-drawer
    ref="registerFormDrawerRef"
    title="新建知识库"
    size="34%"
    confirmText="创建"
    destroyOnClose
    @submit="registerOnSubmit"
  >
    <el-form
      :model="registerForm"
      ref="registerFormRef"
      :rules="registerRules"
      label-width="100px"
      size="small"
      label-position="top"
    >
      <el-form-item prop="knowledge_name" label="知识库名称">
        <el-input
          size="large"
          v-model="registerForm.knowledge_name"
          placeholder="知识库名称"
        />
      </el-form-item>
      <el-form-item prop="embedding_server_id" label="向量抽取服务">
        <!-- <el-input
          size="large"
          v-model="registerForm.embedding_server_id"
          placeholder="向量选择服务"
        /> -->
        <el-select
          v-model="registerForm.embedding_server_id"
          filterable
          size="large"
          :name="selectEmbeddingName"
          :filter-method="remoteMethod"
          :loading="isScrollLoadingEmbedding"
          loading-text="正在努力寻找"
          no-data-text="臣妾支持不了哇"
          no-match-text="臣妾支持不了哇"
        >
          <el-option
            v-for="item in selectEmbeddingServer"
            :key="item.id"
            :label="item.embedding_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="description" label="描述">
        <el-input
          size="large"
          v-model="registerForm.description"
          placeholder="描述"
        />
      </el-form-item>
    </el-form>
  </form-drawer>
</template>

<script setup>
import FormDrawer from '~/components/FormDrawer.vue'
import { ref, onMounted } from 'vue'
import { ElLoading } from 'element-plus'
import { Search, Plus, More } from '@element-plus/icons-vue'
import { KnowledgeList, EmbeddingServer, KnowledgeDelete } from '~/api/manager'
import { pa } from 'element-plus/es/locale/index.mjs'
import { knowledgeCreate } from '~/composables/knowledgeManger'
import { useRouter } from 'vue-router'

const {
  formDrawerRef: registerFormDrawerRef,
  formRef: registerFormRef,
  form: registerForm,
  onSubmit: registerOnSubmit,
  rules: registerRules,
  openRegisterForm
} = knowledgeCreate()
const knowledges = ref([]) // 知识库列表
const query_name = ref('')
const page = ref(1)
const limit = ref(15)
const knowledges_content = ref(0)
const router = useRouter()

// 向量抽取下拉框部分
const selectEmbeddingServer = ref([])
const selectPgae = ref(1)
const selectLimit = ref(10)
const selectCount = ref(0)
const selectEmbeddingName = ref('')
const isScrollLoadingEmbedding = ref(false)

// 进度条部分
const percentage = ref(0)

const customColorMethod = () => {
  if (percentage.value < 30) {
    return '#5cb87a'
  }
  if (percentage.value < 60) {
    return '#f7b500'
  }
  if (percentage.value < 90) {
    return '#f56c6c'
  }
  return '#e01e5a'
}

// 向量服务分页获取
const get_selectEmbeddingServer = async () => {
  isScrollLoadingEmbedding.value = true
  EmbeddingServer({
    page: selectPgae.value,
    limit: selectLimit.value,
    name: selectEmbeddingName.value
  })
    .then((res) => {
      console.log(res)
      selectEmbeddingServer.value = res.data
      selectCount.value = res.count
    })
    .finally(() => {
      isScrollLoadingEmbedding.value = false
    })
}

// 远程搜索方法
const remoteMethod = async (query) => {
  selectPgae.value = 1
  selectLimit.value = 10
  selectCount.value = 0
  selectEmbeddingName.value = query
  await get_selectEmbeddingServer()
  selectEmbeddingName.value = ''
  console.log(selectEmbeddingServer.value)
}

// 点击三个点
const handleCommand = (command) => {
  if (command.action === 'detail') {
    goToDetail(command.id)
  } else if (command.action === 'delete') {
    const loadingInstance = ElLoading.service({ fullscreen: true })
    console.log('删除知识库', command.id)
    KnowledgeDelete(command.id).then((res) => {
    }).finally(() => {
      loadingInstance.close()
      get_knowledge()
    })

  }
}

const truncateLabel = (label, maxNum) => {
  return label.length > maxNum ? label.slice(0, maxNum) + '...' : label
}

const get_knowledge = () => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  KnowledgeList({
    page: page.value,
    limit: limit.value,
    name: query_name.value
  })
    .then((res) => {
      console.log(res)
      knowledges.value = res.data
      knowledges_content.value = res.count
      percentage.value = ((res.count / 30) * 100).toFixed(2)
    })
    .finally(() => {
      loadingInstance.close()
    })
}
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // Months are 0-based
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const inputKeySearch = () => {
  page.value = 1
  get_knowledge()
}

const goToDetail = (id) => {
  console.log(id)
  router.push(`/knowledge/${id}`)
}

onMounted(() => {
  get_knowledge()
  // get_selectEmbeddingServer()
})
</script>

<style scoped>
.container {
  padding: 10px;
}

.search-container {
  display: flex;
  justify-content: space-between; /* 让按钮和搜索框分别靠左和靠右 */
  margin-bottom: 10px;
}

.search-input {
  width: 250px;
  margin-right: 10px; /*距离右边距 0px*/
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 1%; /* 卡片之间的间距 */
  overflow-y: auto; /* 允许垂直滚动 */
  height: 600px;
  max-height: 600px; /* 设置最大高度以启用滚动 */
  box-sizing: border-box; /* 防止 padding 和 margin 影响宽度 */
}

.card {
  max-height: 150px;
  width: 19%; /* 每个卡片的宽度为 19% */
  margin-bottom: 1%; /* 卡片之间的间距 */
  border-radius: 13px; /* 添加圆角 */
}

.update-date {
  font-size: 15px; /* 调整为你需要的大小 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  font-size: 16px; /* 调整图标大小 */
}

.el-icon-more {
  color: #666; /* 调整图标颜色 */
}
</style>
